<%@ page import="com.cinsea.form.service.FormService" %>
<%@ page import="com.cinsea.file.service.FilestoreService" %>
<%@ page import="com.cinsea.report.service.ReportfieldService" %>
<%@ page import="com.cinsea.security.service.RightService" %>
<%@ page import="com.cinsea.query.service.SavedqueryService" %>
<%@ page import="com.cinsea.report.service.ReportService" %>
<%@ page import="com.cinsea.query.model.Savedquery" %>
<%@ page import="com.cinsea.report.model.Report" %>
<%@ page import="com.cinsea.report.model.Reportfield" %>
<%@ page import="com.cinsea.form.model.Formfield" %>
<%@ page import="com.cinsea.report.service.ReportSearchfieldService" %>
<%@ page import="com.cinsea.report.model.Reportsearchfield" %>
<%@ page import="com.cinsea.form.service.FormfieldService" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ include file="/common/common.jsp"%>
<%
int pageSize=20;
int gridWidth=700;
int gridHeight=330;
String reportid = request.getParameter("reportid");
String sqlwhere= StringUtil.null2String(request.getParameter("sqlwhere"));
String showCheckbox= StringUtil.null2String(request.getParameter("showCheckbox"));
String isshow= StringUtil.null2String(request.getParameter("isshow")) ; //isshow=0表示默认不加载出数据
String savedqueryid = StringUtil.null2String(request.getParameter("savedqueryid"));
Page pageObject = (Page) request.getAttribute("pageObject");
Map summap = (Map)request.getAttribute("sum");
String isnew=request.getParameter("isnew");
paravaluehm = (HashMap)request.getAttribute("paravaluehm");
if(paravaluehm==null){
	paravaluehm = new HashMap();
}
FormfieldService formfieldService = (FormfieldService) Env.getBean("formfieldService");
ReportfieldService reportfieldService = (ReportfieldService) Env.getBean("reportfieldService");
RightService rightService = (RightService) Env.getBean("rightService");
BrowserService browserService = (BrowserService) Env.getBean("browserService");
FilestoreService filestoreService = (FilestoreService) Env.getBean("filestoreService");
FormService formService=(FormService) Env.getBean("formService");
HumanService humanService=(HumanService) Env.getBean("humanService");
ReportService reportService = (ReportService) Env.getBean("reportService");
SavedqueryService savedqueryService = (SavedqueryService) Env.getBean("savedqueryService");
if(StringUtil.isEmpty(savedqueryid)){
    List<Savedquery> savedqueryList = savedqueryService.getSavedquerys("from Savedquery where reportid='"+reportid+"' and userid='"+Env.getRemoteUser().getCurrentuserid()+"' and bepublic='0' and bedefault=1 order by objorder");
    if(savedqueryList.size()!=0){
        savedqueryid = savedqueryList.get(0).getId();
    }else{
        savedqueryList = savedqueryService.getSavedquerys("from Savedquery where reportid='"+reportid+"' and bepublic='1' and bedefault=1 order by objorder");
        if(savedqueryList.size()!=0){
            savedqueryid = savedqueryList.get(0).getId();
        }
    }
}
List reportfieldList = reportfieldService.getReportfieldListForUser(reportid,savedqueryid);
 Report report=reportService.getReport(reportid);
 String datastatus= StringUtil.null2String(request.getParameter("datastatus"));
 String isdatastatus= StringUtil.null2String(request.getParameter("isdatastatus"));
if(reportfieldList.size()==0){
	reportfieldList = reportfieldService.getReportfieldListByReportID(reportid);
}
String formid=reportService.getReport(reportid).getFormid();
Form form=formService.getFormById(formid);
int rows=0;
int cols=0;
List reportdatalist = new ArrayList();//用于保存转换后的查询数据

String jsonStr=null;
Map fieldsearchMap = (Map)request.getAttribute("fieldsearchMap");
if(fieldsearchMap != null){
        Map jsonObject=new HashMap();
        Set keySet=fieldsearchMap.keySet();
        for(Object key:keySet){
            String value=(String)fieldsearchMap.get(key);
            if(!StringUtil.isEmpty(value))
            jsonObject.put(key,value);
        }
        if(!"".equals(sqlwhere.trim())){
        jsonObject.put("sqlwhere",sqlwhere);
        }
        jsonStr= JSON.toJSONString(jsonObject);
    }
    boolean isauth = (form.getObjtype()==4)?false: rightService.checkOpttype(reportid,6);
%>

<html>
<head>
<%@include file="/common/head.jsp"%>
<style type="text/css">
      a { color:blue; cursor:pointer; }
</style>
<script src='${ctx}/dwr/interface/DataService.js'></script>
<script src='${ctx}/dwr/interface/OptionService.js'></script>
<script src='${ctx}/dwr/util.js'></script>
<script type="text/javascript">
    var store;
    var selected=new Array();
    var dlg0;
   var viewport=null;
    <%

String action = request.getContextPath()+"/reportdata.do?action=search&from=list&isnew="+isnew+"&reportid=" + reportid;
String action2 = request.getContextPath()+"/reportdata.do?&isnew="+isnew+"&action=search&reportid=" + reportid+"&savedqueryid="+savedqueryid;
String tmpaction = request.getContextPath()+"/report/querytemplatelist.jsp?reportid="+reportid;

        String cmstr="";
        String fieldstr="";
        Iterator it = reportfieldList.iterator();
        cols = reportfieldList.size();
        if(form.getObjtype()!=4)fieldstr+="'processid'";//非虚拟表单才添加processid字段
        Map reporttitleMap = new HashMap();
       int k=0;
		while(it.hasNext()){
			Reportfield reportfield = (Reportfield) it.next();
			reporttitleMap.put(reportfield.getDisplayname(),reportfield.getDisplayname());
			Integer showwidth = reportfield.getWidth();
			String widths = "";
			if(showwidth!=null && showwidth.intValue()!=-1){
				widths = "width=" + showwidth + "%";
			}
			Formfield formfields = formfieldService.getFormfieldById(reportfield.getFieldid());
			String thtmptype = "";
			if(formfields.getDisplaytype() != null){
				thtmptype = formfields.getDisplaytype().toString();
			}
			String tfieldtype = "";
			if(formfields.getDatatype()!=null){
				tfieldtype = formfields.getDatatype().toString();
			}

			String styler = "";
			if("1".equals(thtmptype) && ("2".equals(tfieldtype) || "3".equals(tfieldtype))){
				styler = "style='text-align :right'";
			}

         	String fieldname=labelService.getLabelName(formfields.getFieldname()) ;
			if(StringUtil.isEmpty(fieldname)){
				fieldname=reportfield.getId();
			}
         	String showname=labelService.getLabelName(reportfield.getDisplayname());
         	int sortable=NumberUtil.getIntegerValue(reportfield.getBeorderfield(),0);
         	if(cmstr.equals(""))
         	{
         	 if(sortable==0)
            cmstr+="{header:'"+showname+"',dataIndex:'"+fieldname+"',width:"+showwidth*gridWidth/100+",sortable:false}";
            else
            cmstr+="{header:'"+showname+"',dataIndex:'"+fieldname+"',width:"+showwidth*gridWidth/100+",sortable:true}";
            }
            else
            {
            if(sortable==0)
            cmstr+=",{header:'"+showname+"',dataIndex:'"+fieldname+"',width:"+showwidth*gridWidth/100+",sortable:false}";
            else
            cmstr+=",{header:'"+showname+"',dataIndex:'"+fieldname+"',width:"+showwidth*gridWidth/100+",sortable:true}";
            }
            if(fieldstr.equals(""))
            fieldstr+="'"+fieldname+"'";
            else
            fieldstr+=",'"+fieldname+"'";
      	k++;
      }
      	reportdatalist.add(reporttitleMap);//生成excel报表时用到

      %>

    <!--页面菜单开始-->
<%
paravaluehm.put("{id}",reportid);
pagemenustr +="addBtn(tb,'"+I18n.getText("quicksearch")+"','S','zoom',function(){onSearch2()});";
pagemenustr +="addBtn(tb,'"+I18n.getText("clear")+"','R','erase',function(){reset()});";
pagemenustr +="addBtn(tb,'"+I18n.getText("advancedsearch")+"','G','zoom',function(){onSearch3()});";
if(report.getExportxsl().intValue()==1){
pagemenustr +="addBtn(tb,'"+I18n.getText("wftransition")+"Excel','E','page_excel',function(){exportExcel()});";

}
PageextendService _pageextendService2 =(PageextendService)Env.getBean("pageextendService");
pagemenustr += _pageextendService2.getPageextendStrExt(reportid,paravaluehm).get(0);



if(pagemenuorder.equals("0")) {
	pagemenustr =_pageextendService2.getPageextendStrExt(theuri,paravaluehm).get(0) + pagemenustr;
}else{
	pagemenustr = pagemenustr + _pageextendService2.getPageextendStrExt(theuri,paravaluehm).get(0);
}
if(isauth&&!isdatastatus.equals("2"))
{
   pagemenustr +="addBtn(tb,'"+I18n.getText("delete")+"','D','delete',function(){onDelete()});";
  }
  if(report.getQuerytemplate()!=null&&report.getQuerytemplate()==1)
 pagemenustr += "addBtn(tb,'"+I18n.getText("template")+I18n.getText("management")+"','M','page_copy',function(){showtemplate()});";
 List contemplateList= (List) request.getAttribute("contemplateList");
 String templatestorestr="";
  if(contemplateList!=null){
        Iterator iteratorObj=contemplateList.iterator();
             while(iteratorObj.hasNext()){
                   Savedquery savedquery = (Savedquery) iteratorObj.next();
                   if(savedquery.getUserid().trim().equals(loginUser.getId().trim())){
                   templatestorestr+=",['"+savedquery.getId()+"','"+savedquery.getObjname()+"("+(savedquery.getBepublic().equals("0")?I18n.getText("private"):I18n.getText("public"))+")']";
                     }
                   }
                   }
                   if(!StringUtil.isEmpty(templatestorestr) ) templatestorestr=templatestorestr.substring(1);

%>
    Ext.onReady(function(){
    <%if(!pagemenustr.equals("")){%>
       var tb = new Ext.Toolbar({id:'toolbar1'});
       tb.render('pagemenubar');
       <%=pagemenustr%>
        tb.add(pagemenutable);
        <%if(isauth){%>
        tb.add(datatable);
        <%}%>
       <%}%>
        function clearAllSelectedCheckbox(){
            var hd = Ext.fly(grid.getView().innerHd).child('div.x-grid3-hd-checker');
            hd.removeClass('x-grid3-hd-checker-on');
            grid.getSelectionModel().clearSelections();
        }
    store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '<%=action2+"&isjson=1&pagesize="+pageSize%>'
        }),
        reader: new Ext.data.JsonReader({
            sql1:'sql1',
            sql2:'sql2',
            root: 'result',
            totalProperty: 'totalCount',
            <% if((StringUtil.isEmpty(isdatastatus)||"0".equals(isdatastatus))&&isauth){%>
            fields: [<%=fieldstr%>,'del']
            <%}else{%>
             fields: [<%=fieldstr%>]
            <%}%>
        }),
        <%if(showCheckbox.equals("true")){%>
        listeners:{datachanged:clearAllSelectedCheckbox},
        <%}%>
        remoteSort: true
    });
    //store.setDefaultSort('id', 'desc');
    <%if(showCheckbox.equals("true")){%>
    var sm=new Ext.grid.CheckboxSelectionModel();
    var cm = new Ext.grid.ColumnModel([sm,<%=cmstr%>]);
    <%}else{%>
    var sm=new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn});
           <% if((StringUtil.isEmpty(isdatastatus)||"0".equals(isdatastatus))&&isauth){
             showCheckbox="true";
           %>

         var sm=new Ext.grid.CheckboxSelectionModel();
       var cm = new Ext.grid.ColumnModel([sm,<%=cmstr%>,{header: "操作",sortable: false,  dataIndex: 'del'}]);
        <%}else if((StringUtil.isEmpty(isdatastatus)||"1".equals(isdatastatus))&&isauth){
            showCheckbox="true";
           %>
          var sm=new Ext.grid.CheckboxSelectionModel();
       var cm = new Ext.grid.ColumnModel([sm,<%=cmstr%>]);
      <%}else if(report.getShowcheckbox().intValue()==1){    //出现checkbox
             showCheckbox="true";
      %>
      var sm=new Ext.grid.CheckboxSelectionModel();
    var cm = new Ext.grid.ColumnModel([sm,<%=cmstr%>]);
     <%}else {%>
          var cm = new Ext.grid.ColumnModel([<%=cmstr%>]);
        <%}%>
    <%}%>
   // cm.defaultSortable = true;

                    var autorefresh=new Ext.ux.grid.AutoRefresher({ interval:'<%=report.getInterval()%>'})
                   var grid = new Ext.grid.GridPanel({
                       region: 'center',
                       store: store,
                       cm: cm,
                       trackMouseOver:false,
                       sm:sm ,
                       loadMask: true,
                       viewConfig: {
                           <%if(reportfieldList.size()>10){%>
                           forceFit:false,
                           <%}else{%>
                             forceFit:true,
                           <%}%>
                           enableRowBody:true,
                           sortAscText:'<%=I18n.getText("sortAscText")%>',
                           sortDescText:'<%=I18n.getText("sortDescText")%>',
                           columnsText:'<%=I18n.getText("columnsText")%>',
                           getRowClass : function(record, rowIndex, p, store){
                               return 'x-grid3-row-collapsed';
                           }
                       },
                       bbar: new Ext.PagingToolbar({
                           pageSize: <%=pageSize%>,
                           <%if(report.getAutorefresh().intValue()==1){%>
                            plugins: autorefresh,
                           <%}%>
            store: store,
            displayInfo: true,
            beforePageText:'<%=I18n.getText("beforePageText")%>',
            afterPageText:'<%=I18n.getText("afterPageText")%>',
            firstText:'<%=I18n.getText("firstText")%>',
            prevText:'<%=I18n.getText("prevText")%>',
            nextText:'<%=I18n.getText("nextText")%>',
            lastText:'<%=I18n.getText("lastText")%>',
            displayMsg:'<%=I18n.getText("displayMsg")%>',
            emptyMsg:'<%=I18n.getText("emptyMsg")%>'
        })
    });
        <%if(report.getAutorefresh().intValue()==1){%>
    store.on('beforeload',function(){
        autorefresh.start();
    });
        <%}%>
    store.baseParams=<%=(jsonStr==null?"{}":jsonStr)%>
     store.baseParams.datastatus='<%=datastatus%>';
    <%if(showCheckbox.equals("true")){%>
    store.on('load',function(st,recs){
        Ext.getDom('sqlstr1').value=st.reader.jsonData.sql1;
        Ext.getDom('sqlstr2').value=st.reader.jsonData.sql2;
        for(var i=0;i<recs.length;i++){
            var reqid=recs[i].get('processid');
        for(var j=0;j<selected.length;j++){
                    if(reqid ==selected[j]){
                         sm.selectRecords([recs[i]],true);
                     }
                 }
    }
    }
            );
    sm.on('rowselect',function(selMdl,rowIndex,rec ){
        var reqid=rec.get('processid');
        for(var i=0;i<selected.length;i++){
                    if(reqid ==selected[i]){
                         return;
                     }
                 }
        selected.push(reqid)
    }
            );
    sm.on('rowdeselect',function(selMdl,rowIndex,rec){
        var reqid=rec.get('processid');
        for(var i=0;i<selected.length;i++){
                    if(reqid ==selected[i]){
                        selected.remove(reqid)
                         return;
                     }
                 }

    }
            );
     <%}else{%>
        store.on('load', function(st, recs) {
            Ext.getDom('sqlstr1').value=st.reader.jsonData.sql1;
            Ext.getDom('sqlstr2').value=st.reader.jsonData.sql2;
        });
     <%}%>
    //Viewport
    //ie6 bug
    Ext.get('divSearch').setVisible(true);
	viewport = new Ext.Viewport({

        layout: 'border',
        items: [{region:'north',autoScroll:true,contentEl:'divSearch',split:true,collapseMode:'mini'},grid]
	});
    var optstore = new Ext.data.SimpleStore({
        id:0,
        fields: ['value', 'text'],
        data : [
            ['0','<%=I18n.getText("create")%><%=I18n.getText("template")%>'],
            ['1','<%=I18n.getText("exist")%><%=I18n.getText("template")%>']
        ]
    });
    var templatestore = new Ext.data.SimpleStore({
        id:0,
        fields: ['value', 'text'],
        data : [<%=templatestorestr%>]
    });
    var typestore = new Ext.data.SimpleStore({
        id:0,
        fields: ['value', 'text'],
        data : [
            ['1','<%=I18n.getText("public")%>'],
            ['0','<%=I18n.getText("private")%>']
        ]
    });
    var yesorno = new Ext.data.SimpleStore({
        id:0,
        fields: ['value', 'text'],
        data : [
            ['1','<%=I18n.getText("yes")%>'],
            ['0','<%=I18n.getText("no")%>']
        ]
    });
    mainform1 = new Ext.FormPanel({
        region:'center',
        id:'mainform1',
        frame:true,
        labelWidth :150,
        autoScroll:true,
        items :[
            {
                xtype:'hidden',
                name: 'reportid',
                value:'<%=reportid%>'
            } ,
            {   fieldLabel:"<%=I18n.getText("opttype")%>",
                xtype:'combo',
                typeAhead: true,
                forceSelection:true,
                value:'0',
                mode:'local',
                triggerAction: 'all',
                store:optstore,
                valueField:'value',
                displayField:'text',
                hiddenName: 'opttype',
                name: 'opttype',
                listeners:{
                            'select':function(f, r, i) {
                                if (i == 0) {
                                    showField(mainform1.form.findField('objname'));
                                    showField(mainform1.form.findField('bepublic'));
                                    showField(mainform1.form.findField('objorder'));
                                    hideField(mainform1.form.findField('templateid'));
                                }
                                else if(i==1){
                                    hideField(mainform1.form.findField('objname'));
                                    hideField(mainform1.form.findField('bepublic'));
                                    hideField(mainform1.form.findField('objorder'));
                                    showField(mainform1.form.findField('templateid'));
                                }
                            }
                        }
            } ,
            {   fieldLabel:"<%=I18n.getText("template")%>",
                xtype:'combo',
                typeAhead: true,
                forceSelection:true,
                mode:'local',
                triggerAction: 'all',
                store:templatestore,
                valueField:'value',
                displayField:'text',
                hiddenName: 'templateid',
                name: 'templateid'
            } ,
            {   fieldLabel:"<%=I18n.getText("query")%><%=I18n.getText("name")%>",
                allowBlank:false,
                blankText:'<%=I18n.getText("mustfill")%>',
                xtype:'textfield',
                name: 'objname'
            } ,
            {   fieldLabel:"<%=I18n.getText("query")%><%=I18n.getText("type")%>",
                xtype:'combo',
                typeAhead: true,
                forceSelection:true,
                value:'0',
                mode:'local',
                triggerAction: 'all',
                store:typestore,
                valueField:'value',
                displayField:'text',
                hiddenName: 'bepublic',
                name: 'bepublic'
            } ,
            {   fieldLabel:"<%=I18n.getText("order")%>",
                xtype:'textfield',
                maskRe : /^\d$/,
                name: 'objorder'
            }
        ]
    });
    formwin = new Ext.Window({
        title:'<%=I18n.getText("query")%><%=I18n.getText("info")%>',
        layout:'border',
        closeAction:'hide',
        plain: true,
        modal :true,
        width:viewport.getSize().width * 0.4,
        height:viewport.getSize().height * 0.4,
        buttons: [
            {text     : '<%=I18n.getText("save")%>',
                handler  : function() {
                    var o = $('#mainForm').serializeArray();
                    var data = {};
                    for (var i = 0; i < o.length; i++) {
                        if (o[i].value != null && o[i].value != "") {
                            data[o[i].name] = o[i].value;
                        }
                    }
                    mainform1.form.submit({
                        url:'<%=action2%>&savequerytemplate=true',
                        params:data ,
                        success:function(f, a) {
                            pop(a.result.msg);
                        },
                        failure:function(f, a) {
                            switch (a.failureType) {
                                case Ext.form.Action.CLIENT_INVALID :
                                    pop('<%=I18n.getText("validatefail")%>!', '<%=I18n.getText("error")%>', 5, 'cross');
                                    break;
                                case Ext.form.Action.CONNECT_FAILURE :
                                    pop('<%=I18n.getText("connectfail")%>!', '<%=I18n.getText("error")%>', 5, 'cross');
                                    break;
                                case Ext.form.Action.SERVER_INVALID :
                                    pop(a.result.msg, '<%=I18n.getText("error")%>', 5, 'cross');
                            }
                        }
                    });
                    formwin.hide();

                }
            },
            {
                text     : '<%=I18n.getText("close")%>',
                handler  : function() {
                    formwin.hide();
                }

            }
        ],
        items:[mainform1]
    });
    formwin.render(Ext.getBody());
        showField(mainform1.form.findField('objname'));
        showField(mainform1.form.findField('bepublic'));
        showField(mainform1.form.findField('objorder'));
        hideField(mainform1.form.findField('templateid'));
        <%
          if(StringUtil.isEmpty(isshow)||!isshow.equals("0")){
        %>
     store.load({params:{start:0, limit:<%=pageSize%>}});
        <%}%>
        dlg0 = new Ext.Window({
                layout:'border',
                closeAction:'hide',
                plain: true,
                modal :true,
                width:viewport.getSize().width*0.8,
                height:viewport.getSize().height*0.8,
                buttons: [{
                    text     : '<%=I18n.getText("close")%>',
                    handler  : function(){
                        dlg0.hide();
                    }

                }],
                items:[{
                id:'dlgpanel',
                region:'center',
                xtype     :'iframepanel',
                frameConfig: {
                    autoCreate:{id:'dlgframe', name:'dlgframe', frameborder:0} ,
                    eventsFollowFrameLinks : false
                },
                autoScroll:true
            }]
            });
});

</script>
</head>
<body style="margin:10px,10px,10px,0px;padding:0px">


<div id="divSearch" style="display:none;">
 <div id="pagemenubar"></div>
<table width="100%" id="pagemenutable" <%if(report.getQuerytemplate()==null||report.getQuerytemplate()!=1){%>style="display:none"<%}%>>
         <tr>
             <td align="right">
                 <a href="javascript:saveTemplate();"><%=I18n.getText("savesearch")%></a>&nbsp;
                 <select id="contemplate" onchange="onSearch4('<%=reportid%>')" style="width:150">
                     <option value="0"><%=I18n.getText("selectplease")%></option>
                     <%
                         if(contemplateList!=null){
                         Iterator itObj=contemplateList.iterator();
                         while(itObj.hasNext()){
                            Savedquery savedquery = (Savedquery) itObj.next();
                     %>
                         <option value="<%=savedquery.getId()%>" <%if(savedquery.getId().equals(savedqueryid)){%>selected="selected"<%}%>><%=savedquery.getObjname()%>(<%if("0".equals(savedquery.getBepublic())){%><%=I18n.getText("private")%><%}else{%><%=I18n.getText("pubic")%><%}%>)</option>
                     <%
                         }
                         }
                     %>
                 </select>
             </td>
         </tr>
     </table>
 <%if(isauth){%>
 <table  id="datatable">
         <tr>
         <td  >
             <%=I18n.getText("data")%><%=I18n.getText("status")%>&nbsp;&nbsp;<select class="inputstyle" id="datastatus" name="datastatus" onchange="datasearch(this.options[this.options.selectedIndex].value)">
                 <%
                     String selected1="";
                     String selected2="";
                     String selected3="";
                 if(StringUtil.isEmpty(datastatus)||(datastatus!=null&&datastatus.equals("0"))){
                    selected1="selected";
                 }else if(datastatus!=null&&datastatus.equals("1"))
                 {
                  selected2="selected";
                 }else{
                     selected3="selected";
                 }
                 %>
                     <option value="0"<%=selected1%>><%=I18n.getText("monitor")%>(<%=I18n.getText("normal")%>)</option>
                    <option value="1"<%=selected2%>><%=I18n.getText("monitor")%>(<%=I18n.getText("delete")%>)</option>
                     <option value="2"<%=selected3%>>N/A</option>
                 </select>
         </td>
         </tr>
     </table>
 <%}%>
 <!--页面菜单结束-->
     <form action="<%=action%>" id="mainForm" name="mainForm" method="post">
     <input type="hidden" id="sqlwhere" name="sqlwhere" value="<%=sqlwhere%>"/>
     <input type="hidden" id="sqlstr1" name="sqlstr1"/>
     <input type="hidden" id="sqlstr2" name="sqlstr2"/>
 <!--条件>
 <%
 //隐藏初使查询条件
 String initsqlwhere = StringUtil.null2String(request.getAttribute("initsqlwhere"));
 String initquerystr = StringUtil.null2String(request.getAttribute("initquerystr"));
 String[] convalue = initquerystr.split("&");
 for(int i=0; i < convalue.length; i++){
     String tempcon = convalue[i];
     if(!StringUtil.isEmpty(tempcon)){
         String[] conv = tempcon.split("=");
         String con = conv[0];
         String vle = "";
         if(conv.length==2){
             vle = conv[1];
         }
         %>
         <input type='hidden' name="<%=con %>" value="<%=vle %>">
         <%
     }
 }
 %>
 <input type='hidden' name="sqlwhere" id="sqlwhere" value="<%=initsqlwhere %>">
 <input type='hidden' name="initquerystr" id="initquerystr" value="<%=initquerystr %>">

 <!--  ***************************************************************************************************************************-->
 <%
 //得到初使查询条件：

 Map hiddenMap = (Map)request.getAttribute("hiddenMap");
 String descorasc = StringUtil.null2String(request.getParameter("descorasc"));//表明前一次是升序还是降序？？
 if(descorasc.equals("desc")){
     descorasc = "asc";
 }else{
     descorasc = "desc";
 }
 String fieldopt = "";
 String fieldopt1 = "";
 String fieldvalue = "";
 String fieldvalue1 = "";

 ReportSearchfieldService reportsearchfieldService=(ReportSearchfieldService) Env.getBean("reportSearchfieldService");

 List reportSearchfieldList = reportsearchfieldService.getReportsearchfieldByReportid2(reportid);
 List formfieldlist = new ArrayList();
 it = reportSearchfieldList.iterator();
  String checkfieldList="";
   StringBuffer directscript=new StringBuffer();
 while(it.hasNext()){

     Reportsearchfield reportsearchfield = (Reportsearchfield) it.next();
     String isfill=reportsearchfield.getMandatory();
     String formfieldid = reportsearchfield.getFieldid();
     Formfield formfield = formfieldService.getFormfieldById(formfieldid);
     if(StringUtil.isEmpty(isfill)||isfill.equals("0"))
                 {
                    formfield.setMandatory("0");
                 }
                 else
                 {
                    formfield.setMandatory("1");
                 }

     formfieldlist.add(formfield);
 }


 DataService dataService = (DataService)Env.getBean("dataService");
 String[] checkcons = request.getParameterValues("check_con");


  %>
 <%if(hiddenMap != null){
   for(Object o:hiddenMap.keySet()){
       String value=(String)hiddenMap.get(o);
 %>
       <input type='hidden' name="<%=o.toString() %>" id="initquerystr" value="<%=value %>">
 <%
   }
 }%>
   <table id="myTable" class="formtable">
     <%
 int linecolor=0;

 int tmpcount = 0;
 boolean showsep = true;

 Iterator fieldit = formfieldlist.iterator();
Map _fieldcheckMap=new HashMap();
while(fieldit.hasNext()){
  Formfield formfield = (Formfield)fieldit.next();
  String _htmltype = StringUtil.null2String(formfield.getDisplaytype());
  String _fieldtype = StringUtil.null2String(formfield.getDatatype());
  String _fieldcheck = StringUtil.null2String(formfield.getValidateexpr());
  String id = formfield.getId();
     if(fieldsearchMap != null){
         fieldopt = (String)fieldsearchMap.get("con"+ id + "_opt");
         fieldopt1 = (String)fieldsearchMap.get("con"+ id + "_opt1");
         fieldvalue = (String)fieldsearchMap.get("con"+ id + "_value");
         fieldvalue1 = (String)fieldsearchMap.get("con"+ id + "_value1");

     }
  if(!_fieldcheck.equals("")&&fieldvalue!=null&&!fieldvalue.equals("")){
     _fieldcheckMap.put(_fieldcheck,fieldvalue);
  }
}
 Iterator fieldit1 = formfieldlist.iterator();
 while(fieldit1.hasNext()){
       String msg="";
     Formfield formfield = (Formfield)fieldit1.next();

     String id = formfield.getId();
     if(fieldsearchMap != null){
         fieldopt = (String)fieldsearchMap.get("con"+ id + "_opt");
         fieldopt1 = (String)fieldsearchMap.get("con"+ id + "_opt1");
         fieldvalue = (String)fieldsearchMap.get("con"+ id + "_value");
         fieldvalue1 = (String)fieldsearchMap.get("con"+ id + "_value1");

     }
     if(formfield.getMandatory().equals("1"))
         {
             if(StringUtil.isEmpty(fieldvalue))
               msg="<img src=\""+request.getContextPath()+"/images/base/checkinput.gif\" align=absMiddle>";
             else
             msg="";
         }


     if(tmpcount%3==0){
 %>
 <tr>
     <%
     }
 String htmltype = String.valueOf(formfield.getDisplaytype());
 String type = formfield.getDatatype();

 String _fieldid = StringUtil.null2String(formfield.getId());
 String _formid = StringUtil.null2String(formfield.getFormid());
 String _fieldname = StringUtil.null2String(formfield.getFieldname());
 String _htmltype = StringUtil.null2String(formfield.getDisplaytype());
 String _fieldtype = StringUtil.null2String(formfield.getDatatype());
 String _fieldattr = StringUtil.null2String(formfield.getDataproperty());
 String _fieldcheck = StringUtil.null2String(formfield.getValidateexpr());
 String _style ="";
 String _value="";
 String htmlobjname = _fieldid;
 %>
     <td  class="formlabel" width=10% nowrap>
 <%
 String label = formfield.getLabelname();
 %>
         <%=labelService.getLabelName(StringUtil.null2String(label))%>
     <%
 if(htmltype.equals("1")){
     if(type.equals("1")){//文本
     if(formfield.getMandatory().equals("1"))
      {
       if(checkfieldList.equals(""))
       checkfieldList+="con"+ id + "_value";
       else
       checkfieldList+=",con"+ id + "_value";
      }
 %>
     <td  class="formvalue" width=15% nowrap>
       <input type=text class=inputstyle style="width:100%" size=30 name="con<%=id%>_value" value="<%=StringUtil.null2String(fieldvalue)%>"<%if(formfield.getMandatory().equals("1")){%>onChange="checkInput('con<%=id%>_value','con<%=id%>_valuespan')"<%}%>/><span <%if(formfield.getMandatory().equals("1")){%>fillin="1"<%}%>  id="con<%=id%>_valuespan"><%=msg%></span>
     </td>
    <%
    }else if(type.equals("2")){//整数
      if(formfield.getMandatory().equals("1"))
      {
       if(checkfieldList.equals(""))
       checkfieldList+="con"+ id + "_value"+",con"+ id + "_value1";
       else
       checkfieldList+=",con"+ id + "_value"+",con"+ id + "_value1";
      }
 %>
     <td  class="formvalue" width=15% nowrap>
       <input type=text class=inputstyle size=5 name="con<%=id%>_value" value="<%=StringUtil.null2String(fieldvalue)%>" onKeyPress='checkInt_KeyPress()' <%if(formfield.getMandatory().equals("1")){%>onChange="checkInput('con<%=id%>_value','con<%=id%>_valuespan')"<%}%>><span <%if(formfield.getMandatory().equals("1")){%>fillin="1"<%}%>  id="con<%=id%>_valuespan"><%=msg%></span>--<%=I18n.getText("to")%>--
       <input type=text class=inputstyle size=5 name="con<%=id%>_value1"   value="<%=StringUtil.null2String(fieldvalue1)%>" onKeyPress='checkInt_KeyPress()'<%if(formfield.getMandatory().equals("1")){%>onChange="checkInput('con<%=id%>_value1','con<%=id%>_valuespan')"<%}%> ><span <%if(formfield.getMandatory().equals("1")){%>fillin="1"<%}%>  id="con<%=id%>_valuespan"><%=msg%></span>
     </td>
     <%
    }
    else if(type.equals("3")){//浮点数

      if(formfield.getMandatory().equals("1"))
      {
       if(checkfieldList.equals(""))
       checkfieldList+="con"+ id + "_value"+",con"+ id + "_value1";
       else
       checkfieldList+=",con"+ id + "_value"+",con"+ id + "_value1";
      }

    %>
     <td  class="formvalue" width=15% nowrap>
       <input type=text class=inputstyle size=5 name="con<%=id%>_value"  value="<%=StringUtil.null2String(fieldvalue)%>" onKeyPress='checkFloat_KeyPress()'<%if(formfield.getMandatory().equals("1")){%>onChange="checkInput('con<%=id%>_value','con<%=id%>_valuespan')"<%}%>><span <%if(formfield.getMandatory().equals("1")){%>fillin="1"<%}%>  id="con<%=id%>_valuespan"><%=msg%></span>--<%=I18n.getText("to")%>--
       <input type=text class=inputstyle size=5 name="con<%=id%>_value1" value="<%=StringUtil.null2String(fieldvalue1)%>" onKeyPress='checkFloat_KeyPress()'<%if(formfield.getMandatory().equals("1")){%>onChange="checkInput('con<%=id%>_value1','con<%=id%>_valuespan')"<%}%> ><span <%if(formfield.getMandatory().equals("1")){%>fillin="1"<%}%>  id="con<%=id%>_valuespan"><%=msg%></span>
     </td>
     <%

    }
    else if(type.equals("4")){//日期
        if(formfield.getMandatory().equals("1"))
      {
       if(checkfieldList.equals(""))
       checkfieldList+="con"+ id + "_value"+",con"+ id + "_value1";
       else
       checkfieldList+=",con"+ id + "_value"+",con"+ id + "_value1";
      }
    %>
             <td  class="formvalue" width=15% nowrap>
                    <input type=text class=inputstyle style="width:45%" size=10 name="con<%=id%>_value"  value="<%=StringUtil.null2String(fieldvalue)%>" onclick="WdatePicker()" <%if(formfield.getMandatory().equals("1")){%>onchange="checkInput('con<%=id%>_value','con<%=id%>_valuespan')"<%}%>>
                    <span id="con<%=id%>_valuespan" <%if(formfield.getMandatory().equals("1")){%>fillin="1"<%}%>  ><%=msg%></span>-
                    <input type=text class=inputstyle style="width:45%" size=10 name="con<%=id%>_value1"  value="<%=StringUtil.null2String(fieldvalue1)%>" onclick="WdatePicker()" <%if(formfield.getMandatory().equals("1")){%>onchange="checkInput('con<%=id%>_value1','con<%=id%>_value1span')"<%}%>>
                    <span id="con<%=id%>_value1span" <%if(formfield.getMandatory().equals("1")){%>fillin="1"<%}%> >
                        <%=msg%>
                    </span>

                 </td>

     <%
    }
    else if(type.equals("5")){//时间
     if(formfield.getMandatory().equals("1"))
      {
       if(checkfieldList.equals(""))
       checkfieldList+="con"+ _fieldid + "_value";
       else
       checkfieldList+=",con"+ _fieldid + "_value";
      }
            StringBuffer sb = new StringBuffer("");
         sb.append("<td width=15% class='FieldValue' nowrap>");
         sb.append("<input type=\"text\" class=inputstyle size=10 name=\"con"+_fieldid+"_value\" value=\""+StringUtil.null2String(fieldvalue)+"\" onclick=\"WdatePicker({startDate:'%H:00:00',dateFmt:'H:mm:ss'})\" ");

          if(formfield.getMandatory().equals("1")){
         sb.append(" onchange=\"checkInput('con"+_fieldid+"_value','con"+_fieldid+"_valuespan')\"><span id=\"con"+_fieldid+"_valuespan\" name=\"con"+_fieldid+"_valuespan\" fillin=1 >");
         }else{
         sb.append("><span id=\"con"+_fieldid+"_valuespan\" name=\"con"+_fieldid+"_valuespan\"  >");
         }
         sb.append(msg);
         sb.append("</span></td>");
            out.print(sb.toString());
    }
      %>
 <%}
 else if(htmltype.equals("2")){//多行文本

 if(tmpcount%3==2){
 %>
     <td colspan=3  class="formvalue" width=15% nowrap>
         <TEXTAREA style="width:200" ROWS="" COLS="50" name="con<%=id%>_value" value="<%=StringUtil.null2String(fieldvalue)%>"<%if(formfield.getMandatory().equals("1")){%>onChange="checkInput('con<%=id%>_value','con<%=id%>_valuespan')"<%}%>  ><%=StringUtil.null2String(fieldvalue)%></TEXTAREA><span <%if(formfield.getMandatory().equals("1")){%>fillin="1"<%}%> id="con<%=id%>_valuespan"><%=msg%></span>
     </td>
  <%}else{%>
     <td colspan=3  class="formvalue" width=15% nowrap>
       <TEXTAREA style="width:100%"  ROWS="" COLS="50" name="con<%=id%>_value" value="<%=StringUtil.null2String(fieldvalue)%>"<%if(formfield.getMandatory().equals("1")){%>onChange="checkInput('con<%=id%>_value','con<%=id%>_valuespan')"<%}%> ><%=StringUtil.null2String(fieldvalue)%></TEXTAREA><span <%if(formfield.getMandatory().equals("1")){%>fillin="1"<%}%> id="con<%=id%>_valuespan"><%=msg%></span>
     </td>
     <%}
 }
 else if(htmltype.equals("3")){//带格式文本



 }

 else if(htmltype.equals("4")){//check框

   if(formfield.getMandatory().equals("1"))
      {
       if(checkfieldList.equals(""))
       checkfieldList+="con"+ id + "_value";
       else
       checkfieldList+=",con"+ id + "_value";
      }
 %>

     <td  class="formvalue" width=15% nowrap>
             <INPUT TYPE="checkbox" NAME="con<%=id%>_value"  <%if(StringUtil.null2String(fieldvalue).equals("1")){%> checked  value="1" <%}%> <%if(formfield.getMandatory().equals("1")){%>onChange="checkInput('con<%=id%>_value','con<%=id%>_valuespan')"<%}%>  flag=0  onclick="gray(this)" ><span <%if(formfield.getMandatory().equals("1")){%>fillin="1"<%}%> id="con<%=id%>_valuespan"><%=msg%></span>
     </td>

     <%}

 else if(htmltype.equals("5")){//选择项
       if(formfield.getMandatory().equals("1"))
      {
       if(checkfieldList.equals(""))
       checkfieldList+="con"+ _fieldid + "_value";
       else
       checkfieldList+=",con"+ _fieldid + "_value";
      }
             List list ;
             if(_fieldcheckMap.get(_fieldid)!=null){
             list = optionService.getOptions2(type,(String)_fieldcheckMap.get(_fieldid));
             }
             else
             list = optionService.getOptions2(type,null);
             StringBuffer sb = new StringBuffer("");
             sb.append("<input type=\"hidden\" name=\""
                             + _fieldid + "_fieldcheck\" value=\"" + _fieldcheck + "\" >");
              if(formfield.getMandatory().equals("1"))
              {
             sb.append("<td width=15% class='formvalue'>\n\r <select class=\"inputstyle2\" style=\"width:100%\" id=\"con"+_fieldid+"_value\"  name=\"con"+_fieldid+"_value\" "+_style+" onchange=\"fillotherselect('"+_fieldtype+"',this,'" + _fieldid
							+ "',"+ "-1" +"),checkInput('con"+_fieldid+"_value','con"+_fieldid+"_valuespan')\">");
				}else{
				  sb.append("<td width=15% class='formvalue'>\n\r <select class=\"inputstyle2\" style=\"width:100%\" id=\"con"+_fieldid+"_value\"  name=\"con"+_fieldid+"_value\" "+_style+" onchange=\"fillotherselect('"+_fieldtype+"',this,'" + _fieldid
							+ "',"+ "-1" +")\">");
				}
             String _isempty = "";
             if(StringUtil.isEmpty(fieldvalue))
                 _isempty = " selected ";
             sb.append("\n\r<option value=\"\" "+_isempty +" ></option>");
             for(int i=0;i<list.size();i++){
                 Option _option = (Option)list.get(i);
                 String _selectvalue = StringUtil.null2String(_option.getId());
                 String _selectname = I18n.getText(StringUtil.null2String(_option.getObjname()));
                 String selected = "";
                 if(_selectvalue.equalsIgnoreCase(StringUtil.null2String(fieldvalue)))
                     selected = " selected ";
                 sb.append("\n\r<option value=\""+_selectvalue+"\" "+selected +" >"+_selectname+"</option>");
             }
             	sb.append("</select> ");
             	if(formfield.getMandatory().equals("1"))
        sb.append("<span id='con"+_fieldid+"_valuespan' fillin=1>");
        else
          sb.append("<span id='con"+_fieldid+"_valuespan'>");
					if (formfield.getMandatory().equals("1"))
					{
					  if(StringUtil.isEmpty(fieldvalue))
						sb.append("<img src=\""+request.getContextPath()+"/images/base/checkinput.gif\" align=absMiddle>");
						else
						;
				    }
					sb.append("</span>");
             sb.append("</td>");
             out.print(sb.toString());

 }
 else if(htmltype.equals("6")){ // 关联选择
                    if(formfield.getMandatory().equals("1"))
      {
       if(checkfieldList.equals(""))
       checkfieldList+="con"+ _fieldid + "_value";
       else
       checkfieldList+=",con"+ _fieldid + "_value";
      }
             Browser browser = browserService.get(type);
             if(browser != null){
                 String _browserid = StringUtil.null2String(browser.getId());
                 String _refurl = StringUtil.null2String(browser.getUrl());
                 String _viewurl = StringUtil.null2String(browser.getDisplayurl());
                 String tablename = StringUtil.null2String(browser.getTablename());
                 String _keyfield = StringUtil.null2String(browser.getKeyfield());
                 String _viewfield = StringUtil.null2String(browser.getDisplayfield());
                  int isdirect=NumberUtil.getIntegerValue(browser.getBeinput(),0).intValue();
                 String _selfield=StringUtil.null2String(browser.getPromptfield());
                 String showname = "";
                 if(!StringUtil.isEmpty(fieldvalue)){
                     String sql = "select " + _keyfield + " as objid," + _viewfield + " as objname from " + tablename + " where " + _keyfield + " in(" + StringUtil.formatMutiIDs(StringUtil.null2String(fieldvalue)) + ")";
                     List valuelist = dataService.getValues(sql);

                     Map tmprefmap = null;
                     String tmpobjname = "";
                     String tmpobjid = "";

                     for(int i=0;i<valuelist.size();i++){
                         tmprefmap = (Map)valuelist.get(i);
                         tmpobjid = StringUtil.null2String((String) tmprefmap.get("objid"));
                         try{
                             tmpobjname = StringUtil.null2String((String) tmprefmap.get("objname"));
                         }catch(Exception e){
                             tmpobjname= ((java.math.BigDecimal)tmprefmap.get("objname")).toString();
                         }

                         if(!StringUtil.isEmpty(_viewurl)){//以里面定义为主

                             showname += "&nbsp;&nbsp;<a href=\""+ _viewurl + tmpobjid +"\" target=\"_blank\" >";
                             showname += tmpobjname;
                             showname += "</a>";

                         }else{
                             if(i==valuelist.size()-1){
                                 showname += tmpobjname;
                             }else{
                                 showname += tmpobjname + ", ";
                             }
                         }
                     }
                 }


                 String checkboxstr = "";
                 if("cs_org".equals(tablename)){
                    if(formfield.getFieldname().equalsIgnoreCase("orgids"))
                    ;
                    else{
                     String checked = "";
                     if(fieldsearchMap!=null&&StringUtil.null2String(fieldsearchMap.get("con" + id + "_checkbox")).equals("1")){
                         checked = "checked";
                     }
					if(StringUtil.null2String(fieldvalue1).equals("1")){
						checked = "checked";
					}
                     checkboxstr = "<input  type=\"checkbox\" name=\"con" + _fieldid+ "_checkbox\" value=\"1\" "+ checked +">";
                     }
                 }
                 StringBuffer sb = new StringBuffer("");
                 sb.append("<td width=15% class='formvalue'> ");
                  if(isdirect==1)
                {
                  //加一个用于提示的文本框
                     sb.append("<input type=text class=\"InputStyle2\" style=\"width:65%\" name="+_fieldid+" id="+_fieldid+" onfocus=\"checkdirect(this)\">");
                    directscript.append(" $(\"#"+_fieldid+"\").autocomplete(\""+request.getContextPath()+"/browser.do?action=getauto&tablename="+tablename+"&viewfield="+_viewfield+"&selfield="+_selfield+"&keyfield="+_keyfield+"\", {\n" +
                                         "\t\twidth: 260,\n" +
                                                    "        max:15,\n" +
                                                    "        matchCase:true,\n" +
                                                    "        scroll: true,\n" +
                                                    "        scrollHeight: 300,          \n" +
                                                    "        selectFirst: false});");


                                 directscript.append("\n" +
                                     "                             $(\"#"+_fieldid+"\").result(function(event, data, formatted) {\n" +
                                     "                                     if (data)\n" +
                                     "                                         document.getElementById('con"+_fieldid+"_value').value=data[1];\n" +
                                     "                                 });");

                }

                 sb.append("\n\r<button  class=Browser type=button onclick=\"getBrowser('con"+_fieldid+"_value','con"+_fieldid+"span','"+_browserid+"','"+_viewurl+"','0');\"></button>");
                  if(isdirect==1)
                 sb.append("\n\r<input type=\"hidden\" id=\"con"+_fieldid+"_value\" name=\"con"+_fieldid+"_value\" value=\""+StringUtil.null2String(fieldvalue)+"\"  "+_style+"  >");
                 else
                  sb.append("\n\r<input type=\"hidden\" id=\"con"+_fieldid+"_value\" name=\"con"+_fieldid+"_value\" value=\""+StringUtil.null2String(fieldvalue)+"\"  "+_style+"  >");
                 if(formfield.getMandatory().equals("1"))
                 sb.append("\n\r<span id=\"con"+_fieldid+"span\" name=\"con"+_fieldid+"span\" fillin=1 >");
                 else
                 sb.append("\n\r<span id=\"con"+_fieldid+"span\" name=\"con"+_fieldid+"span\" >");
                 sb.append(showname);
                 sb.append(msg);
                 sb.append("</span>\n\r").append(checkboxstr).append("</td> ");
                 out.print(sb.toString());

             }
 }
 else if(htmltype.equals("7")){ //附件
    if(formfield.getMandatory().equals("1"))
      {
       if(checkfieldList.equals(""))
       checkfieldList+="con"+ _fieldid + "_value";
       else
       checkfieldList+=",con"+ _fieldid + "_value";
      }
             StringBuffer sb = new StringBuffer("");
             sb.append("<td> \n\r<input type=\"hidden\" name=\""+_fieldid+"\" value=\""+_value+"\" >");
             if(!StringUtil.isEmpty(_value)){
                 Filestore filestore = filestoreService.getAttach(_value);
                 String attachname = StringUtil.null2String(filestore.getObjname());
                 sb.append("\n\r<a href=\""+request.getContextPath()+"/filedownload.do?attachid="+_value+"\">"+attachname+"</a>");
             }
           sb.append("\n\r<input type=\"file\" class=\"inputstyle2\" name=\"con"+_fieldid+"file\" "+_style+" onchange=checkInput('con"+_fieldid+"file','con"+_fieldid+"span')>");
            if(formfield.getMandatory().equals("1"))
           sb.append("\n\r<span id=\"con"+_fieldid+"span\" name=\"con"+_fieldid+"span\" fillin=1>");
           else
            sb.append("\n\r<span id=\"con"+_fieldid+"span\" name=\"con"+_fieldid+"span\">");
            if(formfield.getMandatory().equals("1"))
            {

             sb.append(msg);

             }
             sb.append("</span>\n\r");
                    sb.append("\n\r</td> ");
             out.print(sb.toString());

 }

  if(linecolor==0) linecolor=1;
           else linecolor=0;

   if(htmltype.equals("2")){
     tmpcount += 2 ;
   }
   else{
     tmpcount += 1;
   }
 }%>
   </table>
 </form>
 </div>
<!-- 条件结束-->
<script type="text/javascript">
      var inputid;
      var spanid;
      var temp;
     function checkdirect(obj)
  {
      inputid=obj.id;
      spanid=obj.name;
      temp=0;
  }
      $(document).ready(function($){
              <%=directscript%>
         $.Autocompleter.Selection = function(field, start, end) {
             if( field.createTextRange ){
              var selRange = field.createTextRange();
              selRange.collapse(true);
              selRange.moveStart("character", start);
              selRange.moveEnd("character", end);
              selRange.select();
              if(inputid==undefined||spanid==undefined)
                 return;
               var len=field.value.indexOf("  ");
                 var lenspance=field.value.indexOf(" ");

                   if(temp==0&&len>0){
                   temp=1;
               var  length=field.value.length;

               var data=field.value;

              document.getElementById(inputid).value=field.value.substring(0,field.value.indexOf("  "));
             document.getElementById('con'+spanid+'span').innerHTML= data.substring(len,length);
                   }else if(temp==0&&lenspance>0){

                 var data=field.value;

              document.getElementById(inputid).value=data;
             document.getElementById('con'+spanid+'span').innerHTML= data;

                   }else{
                       document.getElementById(inputid).value="";
                   }
       } else if( field.setSelectionRange ){
              field.setSelectionRange(start, end);
          } else {
                 if( field.selectionStart ){
                  field.selectionStart = start;
                  field.selectionEnd = end;
              }
          }
          field.focus();
      };

       });

  </script>

  <script language="javascript" type="text/javascript">
   function onSearch(pageno){
          document.mainForm.pageno.value=pageno;
       document.mainForm.submit();
   }
   function createexcel(){
          document.mainForm.action="${ctx}/reportdata.do?action=createexcel&reportid=<%=reportid%>&exportflag=";
       document.mainForm.submit();
   }

   function onSearch2(){
        var o=$('#mainForm').serializeArray();
       var data={};
       for(var i=0;i<o.length;i++) {
           if(o[i].value!=null&&o[i].value!=""){
           data[o[i].name]=o[i].value;
           }
       }
     checkfields='<%=checkfieldList%>';
    checkmessage="<%=I18n.getText("mustfill")%>";
    if(checkForm(mainForm,checkfields,checkmessage)){


	   		 store.baseParams=data;
        store.baseParams.datastatus='<%=datastatus%>';
       store.load({params:{start:0, limit:<%=pageSize%>}});
	  }
       event.srcElement.disabled = false;
   }
   $(document).keydown(function(event) {
       if (event.keyCode == 13) {
          onSearch2();
       }
   });

   function onSearch3(){
          document.getElementById('mainForm').action="${ctx}/report/reportsearch.jsp?reportid=<%=reportid%>";
       document.getElementById('mainForm').submit();
   }
   function reset(){
         $('#mainForm span').text('');
         $('#mainForm input[type=text]').val('');
         $('#mainForm textarea').val('');
         $('#mainForm input[type=checkbox]').each(function(){
             this.checked=false;
         });
         $('#mainForm input[type=hidden]').each(function(){
             if(this.name.indexOf('con')==0)
             this.value='';
         });
         $('#mainForm select').val('');
         $('#mainForm span[fillin=1]').each(function(){
             this.innerHTML='<img src=${ctx}/images/base/checkinput.gif>';
         });
   }

   function fillotherselect(selectid,elementobj, fieldid, rowindex) {
           var elementvalue = Trim(getValidStr(elementobj.value));//选择项的值
           var objname = "" + fieldid + "_fieldcheck";
           var fieldcheck = Trim(getValidStr(document.getElementById(objname).value));//用于保存选择项子项的值(formfieldid)
           if (fieldcheck == "")
               return;
           OptionService.getOptions(selectid,elementvalue,{
         callback:function(dataFromServer) {
           createList(selectid,dataFromServer, fieldcheck,rowindex);
         }
       });
       }
       function createList(selectid,data, fieldcheck, rowindex)
       {
           var select_array = fieldcheck.split(",");
           for (loop = 0; loop < select_array.length; loop++) {
               var objname = "con" + select_array[loop] + "_value";
               if (rowindex != -1)
                   objname += "_" + rowindex;

               if (document.getElementById(objname) == null) {
                   return;
               }
               dwr.util.removeAllOptions(objname);
               dwr.util.addOptions(objname, data,"id","objname");
               fillotherselect(selectid,document.getElementById(objname), select_array[loop], rowindex);
           }
       }

  function getBrowser(inputname,inputspan,browserid,viewurl,isneed){

	var idsin = document.getElementsByName(inputname)[0].value;
	var id;
    try{
         var url ='${ctx}/browser/browser.jsp?id='+browserid+'&idsin='+idsin;
            if (idsin.length > 900) {   //当idsin过长时，ie的url不支持过长的地址
                url ='${ctx}/browser/browser.jsp?id='+browserid;
            }
    id=showDialog(url);
    }catch(e){return}
    if (id!=null) {

    if (id[0] != '0') {
		document.getElementById(inputname).value = id[0];
		document.getElementById(inputspan).innerHTML = id[1];

    }else{
		document.getElementById(inputname).value = '';
		if (isneed=='0')
		document.getElementById(inputspan).innerHTML = '';
		else
		document.getElementById(inputspan).innerHTML = '<img src=${ctx}/images/base/checkinput.gif>';

            }
         }
    }


   function delone(processid)
   {
       var processid=processid

     Ext.MessageBox.confirm('', '<%=I18n.getText("deleteConfirm")%>', function (btn, text) {
             if (btn == 'yes') {
                 Ext.Ajax.request({
                     url: '${ctx}/reportdata.do?action=delone',
                     params:{processid:processid,reportid:'<%=reportid%>'},
                     success: function(res) {
                        if(res.responseText == 'noright')
                         {
                           Ext.MessageBox.alert('', '<%=I18n.getText("noright")%>',function(){

                            }) ;
                         }else{
                         selected = [];
                          store.baseParams=<%=(jsonStr==null?"{}":jsonStr)%>
                         store.baseParams.datastatus='<%=isdatastatus%>';
                         store.load({params:{start:0, limit:20}});
                         }
                     }
                 });
             }
         });
   }
     function onDelete()
     {
         if (selected.length == 0) {
             Ext.MessageBox.alert('', '<%=I18n.getText("selectConfirm")%>');
             return;
         }

         Ext.MessageBox.confirm('', '<%=I18n.getText("deleteConfirm")%>', function (btn, text) {

             if (btn =='yes') {
                 Ext.Ajax.request({
                     url: '${ctx}/reportdata.do?action=delete',
                     params:{ids:selected.toString(),reportid:'<%=reportid%>',datastatus:'<%=isdatastatus%>'},
                     success: function(res) {
                         if(res.responseText == 'noright')
                         {
                           Ext.MessageBox.alert('', '<%=I18n.getText("noright")%>',function(){

                            }) ;
                         }else{
                         selected = [];
                          store.baseParams=<%=(jsonStr==null?"{}":jsonStr)%>
                         store.baseParams.datastatus='<%=isdatastatus%>';
                         store.load({params:{start:0, limit:20}});
                         }
                     }
                 });
             }
         });

     }
   function datasearch(value){
       var isdatastatus=value;
     location.href="<%=action2%>&isdatastatus="+isdatastatus+"&datastatus="+value;
   }
   function onSearch4(reportid){
       var savedqueryid=document.getElementById("contemplate").value;
          location.href="<%=action2.substring(0,action2.indexOf("&savedqueryid="))%>&savedqueryid="+savedqueryid;
   }
   function searchOperate(){
       var searchOperate=document.getElementById("searchOperate");
       if(searchOperate.value=="0"){
           document.getElementById("objnametr").style.display="block";
           document.getElementById("publictr").style.display="block";
           document.getElementById("objdesctr").style.display="block";
           document.getElementById("mycontemplate").style.display="none";
       }else{
           document.getElementById("objnametr").style.display="none";
           document.getElementById("publictr").style.display="none";
           document.getElementById("objdesctr").style.display="none";
           document.getElementById("mycontemplate").style.display="block";
       }
   }
   function openchild(url)
  {
    this.dlg0.getComponent('dlgpanel').setSrc("${ctx}"+url);
    this.dlg0.show();
  }


   function saveTemplate(){
        this.formwin.show()
 }


      function exportExcel(){
          document.forms[0].action="${ctx}/excelupload.do?reportid=<%=reportid%>&action=reportExport&savedqueryid=<%=savedqueryid%>";
          document.forms[0].submit();
      }
 function gray(obj)
{
switch(obj.flag)
{
//当flag为0时,为未选中状态
case '0':obj.checked=true;obj.indeterminate=true;obj.flag='2';
      obj.value='2';
    break;
//当flag未1时,为白色选中状态
case '2':obj.checked=true;obj.indeterminate=false;obj.flag='1';
        obj.value='1';
    break;
//当flag为2时,为灰色选中状态  (找出所有的数据)
case '1':obj.checked=false;obj.indeterminate=false;obj.flag='0';
    obj.value='0';
    break;
}
}
  function showtemplate(){
      onUrl('<%=tmpaction%>','<%=I18n.getText("template")%><%=I18n.getText("management")%>')

}
   </script>
<%=StringUtil.null2String(report.getJavascript())%>
<script type="text/javascript" language="javascript" src="<%= request.getContextPath()%>/datapicker/WdatePicker.js"></script>
<script>
    Ext.onReady(function () {
        toolbar = Ext.getCmp('toolbar1');
        toolbar.addFill();
        var refreshbtn = new Ext.Button({
            text:'刷新',
            iconCls :Ext.ux.iconMgr.getIcon('reload'),
            handler:function () {
                    onSearch2();
            }
        });
        toolbar.add(refreshbtn);
    })
</script>
  </body>
</html>